/**
 * Created by leyvi on 2014/12/2 0002.
 */
var redis = require('redis');
var config = require('../../../config');
var Promise = require('promise');
var logger = require('log4js').getLogger('redisDb.js');
var redisDb = {}, client;

(function (host, port, options) {
    client = redis.createClient(
        port ? port : config.redis.port,
        host ? host : config.redis.host,
        options ? options : {
            auth_pass: config.redis.password,
            db: config.redis.database
        }
    );
})();

var quit = function () {
    client.quit(function (err, res) {
        logger.debug('redis command quit, res:' + res);
    });
};


client.on('error', function (error) {
    //client.emit('disconnect');
    logger.error('redis error : ' + error);
});

redisDb.client = client;

redisDb.EXPIRES_DAY = 86400;

redisDb.get = function (key) {
    return new Promise(function (fulfill, reject) {
        client.get(key, function (err, reply) {
            if (err) {
                reject(err);
            } else {
                fulfill(reply);
            }
        });
    });
};

redisDb.setex = function (key, value, expires) {
    client.setex(key, expires, value, redis.print);
};

redisDb.set = function (key, value) {
    client.set(key, value, redis.print);
};

redisDb.del = function(key){
    client.del(key, redis.print);
};

redisDb.llen = function (key) {
    return new Promise(function (fulfill, reject) {
        client.llen(key, function (err, reply) {
            if (err) {
                reject(err);
            } else {
                fulfill(reply);
            }
        });
    });
};

redisDb.rpop = function (key) {
    return new Promise(function (fulfill, reject) {
        client.rpop(key, function (err, reply) {
            if (err) {
                reject(err);
            } else {
                fulfill(reply);
            }
        });
    });
};

redisDb.lpush = function (key, value) {
    //client.lpush(key, value, redis.print);
    return new Promise(function (fulfill, reject) {
        client.lpush(key, value, function (err, reply) {
            if (err) {
                reject(err);
            } else {
                fulfill(reply);
            }
        });
    });
};

redisDb.exists = function (key) {
    return new Promise(function (fulfill, reject) {
        client.exists(key, function (err, reply) {
            if (err) {
                reject(err);
            } else {
                fulfill(reply);
            }
        });
    });
};

/*-----------------------redis锁------------------*/
function getLockExpire(timeout){
    if(timeout){
        return new Date().getMilliseconds()+timeout;
    }else{
        //默认5分钟过期
        return new Date().getMilliseconds()+300000;
    }

}
redisDb.getset = function (key) {
    return new Promise(function (fulfill, reject) {
        client.getset(key, function (err, reply) {
            if (err) {
                reject(err);
            } else {
                fulfill(reply);
            }
        });
    });
};


redisDb.isLock = function(key,timeout){
    return new Promise(function(fulfill,reject){
        client.setnx(key,getLockExpire(timeout),function(err,reply){
            if(reply==1){
                fulfill(false);
                return;
            }else{
                var oldExpire;
                redisDb.get(key).then(function(time1){
                    if(time1&&time1<new Date().getMilliseconds()){
                        oldExpire = time1;
                        return redisDb.getset(key,getLockExpire(timeout));
                    }else{
                        return Promise.resolve(null);
                    }
                }).done(function(time2){
                    if(time2&&time2==oldExpire){
                        fulfill(false);
                    }else{
                        fulfill(true);
                    }
                },function(err){
                    reject(err);
                });
            }
        })
    });

};


module.exports = redisDb;
